package cn.datawin.cmppclient.sender.handler;

import cn.datawin.cmppclient.sender.entity.Provider;
import cn.datawin.cmppclient.sender.service.ProviderService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.drondea.sms.channel.ChannelSession;
import com.drondea.sms.message.IMessage;
import com.drondea.sms.message.cmpp.CmppConnectResponseMessage;
import com.drondea.sms.type.DefaultEventGroupFactory;
import com.drondea.sms.type.ICustomHandler;
import com.drondea.sms.type.UserChannelConfig;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.Date;
import java.util.concurrent.ScheduledExecutorService;


/**
 * cmpp的定制处理器
 **/
@Slf4j
public class CmppClientCustomHandler extends ICustomHandler {

    private Provider provider;

    public CmppClientCustomHandler(Provider provider) {
        this.provider = provider;
    }

    @Override
    public void fireUserLogin(Channel channel, ChannelSession channelSession) {
        log.debug("cmpp通道【{}】登录成功--开始发送短信", provider.getName());
    }

    @Override
    public void channelClosed(ChannelSession channelSession) {
//        GlobalHandler.CMPP_CLIENT_BUSINESS_HANDLER.modifySessionStatus(SessionStatus.DISCONNECT, provider.getNo());


		//TODO 插入连接关闭日志
		/*Date curDate = new Date();
        ScheduledExecutorService executor = DefaultEventGroupFactory.getInstance().getScheduleExecutor();
        executor.submit(() -> {
            try {
                ResProviderConnectLogService resProviderConnectLogService = SpringContextUtil.getBean(ResProviderConnectLogService.class);
                ResProviderConnectLog resProviderConnectLog = new ResProviderConnectLog();
                resProviderConnectLog.setProviderId(Long.valueOf(provider.getNo()));
                resProviderConnectLog.setStatus(-1);
                resProviderConnectLog.setCreateTime(curDate);
                resProviderConnectLogService.insert(resProviderConnectLog);
            } catch (Exception e) {
                log.error("插入连接日志失败", e);
            }
        });*/
    }

    @Override
    public void configPipelineAfterLogin(ChannelPipeline pipeline) {
        //cmpp的回执和上行短信处理
//        pipeline.addLast("cmppClientBusinessHandler", GlobalHandler.CMPP_CLIENT_BUSINESS_HANDLER);
        pipeline.addLast("cmppClientBusinessHandler", SpringUtil.getBean(CmppClientBusinessHandler.class));
    }

    @Override
    public void responseMessageExpired(Integer sequenceId, IMessage request) {
        log.debug("短信超时处理 {}", sequenceId);
    }

    @Override
    public void slidingWindowException(ChannelSession session, ChannelHandlerContext ctx, IMessage message, ChannelPromise promise, Exception exception) {
        log.error("slidingWindowException", exception);
    }

    @Override
    public boolean customLoginValidate(IMessage message, UserChannelConfig channelConfig, Channel channel) {
        Date curDate = new Date();
        ScheduledExecutorService executor = DefaultEventGroupFactory.getInstance().getScheduleExecutor();
        executor.submit(() -> {
            CmppConnectResponseMessage responseMessage = (CmppConnectResponseMessage) message;
//            GlobalHandler.CMPP_CLIENT_BUSINESS_HANDLER.modifySessionStatus(SessionStatus.valueOf((byte) responseMessage.getStatus()),
//                    provider.getNo());
            try {

				//TODO 插入连接登录日志

                /*ResProviderConnectLogService resProviderConnectLogService = SpringContextUtil.getBean(ResProviderConnectLogService.class);
                ResProviderConnectLog resProviderConnectLog = new ResProviderConnectLog();
                resProviderConnectLog.setProviderId(Long.valueOf(provider.getNo()));
                resProviderConnectLog.setStatus((int) responseMessage.getStatus());
                resProviderConnectLog.setCreateTime(curDate);
                resProviderConnectLogService.insert(resProviderConnectLog);*/

				//插入预警日志
                if (responseMessage.getStatus() != 0) {
                    ProviderService providerService = SpringUtil.getBean(ProviderService.class);
                    Document document = new Document();
                    document.put("_id", new ObjectId());
                    document.put("warnType", 1);
                    document.put("providerId", Long.valueOf(provider.getNo()));
                    document.put("warnContent", "连接失败！连接响应状态码：" + responseMessage.getStatus());
                    document.put("status", 0);
                    document.put("createTime", DateUtil.now());
                    providerService.insertEarlyWarning(document);
                }
            } catch (Exception e) {
                log.error("插入连接日志失败", e);
            }
        });
        return true;
    }

}
